package cn.wolfcode.car.business.service.impl;


import cn.wolfcode.car.business.domain.Statement;
import cn.wolfcode.car.business.domain.StatementItem;
import cn.wolfcode.car.business.mapper.StatementItemMapper;
import cn.wolfcode.car.business.mapper.StatementMapper;
import cn.wolfcode.car.business.query.StatementItemQuery;
import cn.wolfcode.car.business.query.StatementQuery;
import cn.wolfcode.car.business.service.IStatementItemService;
import cn.wolfcode.car.business.service.IStatementService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class StatementItemServiceImpl implements IStatementItemService {

    @Autowired
    private StatementItemMapper statementItemMapper;

    @Autowired
    private StatementMapper statementMapper;


    @Override
    public List<StatementItem> selectForList(StatementItemQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return statementItemMapper.selectForList(qo);
    }

    @Override
    public void saveItems(List<StatementItem> list) {
        //1.从集合中的最后一个元素中把优惠金额拿出来 , 还有结算单的id
        StatementItem statementItem = list.remove(list.size() - 1);
        Long statementId = statementItem.getStatementId();
        BigDecimal discountAmount = statementItem.getItemPrice();

        //在计算之前删除旧的数据,添加新的数据,防止添加重复的数据     deleteRelation=>意思就是删除关系,删除中间表中的数据
        statementItemMapper.deleteRelation(statementId);
        //总金额
        BigDecimal totalAmount = new BigDecimal("0");
        //总数量
        BigDecimal totalCount = new BigDecimal("0");
        for (StatementItem item : list) {
            //计算出总金额
            totalAmount = totalAmount.add(item.getItemPrice().multiply(item.getItemQuantity()));
            //总数量
            totalCount = totalCount.add(item.getItemQuantity());
            //把数据存入中间表总
            statementItemMapper.insert(item);
        }
        //修改总金额,总数量,优惠金额 , 通过id去结算单修改数据
        statementMapper.updateAmount(totalAmount,totalCount,discountAmount,statementId);
    }

    @Override
    public void pay(Long statementId) {
        //根据id查询出结算单
        Statement statement = statementMapper.selectByPrimaryKey(statementId);
        //判断结算单的状态必须是消费中的状态
        if (!statement.getStatus().equals(Statement.STATUS_CONSUME)) {
            throw new BusinessException("非法操作");
        }
        //修改结算单的状态,支付人,支付时间
        statementMapper.changePayStatus(statementId , Statement.STATUS_PAID , ShiroUtils.getUserId());
    }
}
